# -*- coding:utf-8 -*-

## ====================================================================
## Copyright (C) 2007-2011  Jean-Philippe GOLAY
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
## ====================================================================


from Tkinter import *
import Pmw
from tkMessageBox import *

from Persistance import *
from iFamily import ItemFamilyListGUI
from iReference import ReferenceListGUI

class ItemGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, hoursListCB=None, minutesListCB=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Article")
		#~ self.iconbitmap(bitmap="/home/fmy/tmp/Donald.ico")
		self.balloon=balloon
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.hoursListCB=hoursListCB
		self.minutesListCB=minutesListCB
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Item-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Item-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tItemGUI\tStart")
		self.makeItem()

	# DEBUT de la gestion du module Item ------------------------------------------------------------------------------------------------------------------
	def clearFieldItem(self):
		# Mise a zéro des champs
		self.itemValues[0].set("")
		self.itemValues[1].set("")
		self.itemValues[2].set("")
		self.listObject=[ItemFamily, Reference, Item]

	def selectItem(self, event):
		if self.listItem.get(0)!="":
			result = Item.select(Item.q.id==self.idListItem[int(self.listItem.curselection()[0])])
			for row in result:
				self.selectedItem = row
			self.listObject[0]=self.selectedItem.itemFamily
			self.listObject[1]=self.selectedItem.reference
			self.listObject[2]=self.selectedItem
			self.itemValues[0].set(self.listObject[0].designation)
			self.itemValues[1].set(self.listObject[1].code)
			if self.selectedItem.designation != None:self.itemValues[2].set(self.selectedItem.designation)
			# activation du bouton supprimer
			self.deleteItemBt.config(state=NORMAL)

	def searchItem(self, event=None):
		if self.searchItemValue.get() != "":
			self.listItem.delete(0,END)
			self.idListItem = []
			result = Item.select(Item.q.designation.startswith(self.searchItemValue.get().encode("utf-8")), orderBy=Item.q.designation)
			for row in result:
				self.listItem.insert(END, str(row.id)+" - "+str(row.reference)+" - "+row.designation)
				self.idListItem.append(row.id)
		else:
			self.listItem.delete(0,END)
			self.idListItem = []
			result = Item.select(orderBy=Item.q.designation)
			for row in result:
				self.listItem.insert(END, str(row.id)+" - "+str(row.reference)+" - "+row.designation)
				self.idListItem.append(row.id)

	def makeItem(self):
		leftFrame = Frame(self)
		# Fiche Article  (présentation colonne de gauche)
		Label(leftFrame, text=u"Fiche Article").pack(side=TOP)
		# Création des champs a renseigner pour un object Item
		itemLabels = (u"Famille", u"Référence", u"Désignation")
		self.itemValues = [StringVar(), StringVar(), StringVar()]
		count = 0
		for name in itemLabels:
			f = Frame(leftFrame)
			Label(f, width=12, text=name, anchor=W).pack(side=LEFT)
			if count == 0: # Famille de Item
				Entry(f, textvariable=self.itemValues[count], width=25, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myFamilyItem=Button(f, image=self.imgSearch, command=lambda x=self.itemValues[count]:self.ctrlListItemFamily(x), padx=4, pady=1)
				myFamilyItem.pack(side=RIGHT)
				self.balloon.bind(myFamilyItem, u"Choisir une Famille d'Article")
			elif count == 1: # Référence
				Entry(f, textvariable=self.itemValues[count], width=25, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myReference=Button(f, image=self.imgSearch, command=lambda x=self.itemValues[count]:self.ctrlListReference(x), padx=4, pady=1)
				myReference.pack(side=RIGHT)
				self.balloon.bind(myReference, u"Choisir une Référence")
			else: 
				Entry(f, textvariable=self.itemValues[count], width=28).pack(side=LEFT, fill=X)
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.saveItemBt=Button(s, image=self.imgSave, command=self.createItem)
		self.saveItemBt.bind("<Return>", self.createItem)
		self.saveItemBt.pack(side=LEFT)
		self.balloon.bind(self.saveItemBt, u"Enregistrer")
		self.deleteItemBt=Button(s, image=self.imgDelete, command=self.deleteItem, state=DISABLED)
		self.deleteItemBt.bind("<Return>", self.deleteItem)
		self.deleteItemBt.pack(side=LEFT)
		self.balloon.bind(self.deleteItemBt, u"Supprimer")
		s.pack(side=TOP, fill=X)        
		# Liste des Item existants (présentation colonne de droite)
		Label(leftFrame, text=u"Liste des Articles").pack()
		self.searchItemValue = StringVar()
		self.searchItemEt = Entry(leftFrame,  width=40, textvariable=self.searchItemValue, relief=GROOVE)
		self.searchItemEt.bind("<KeyRelease>", self.searchItem)
		self.searchItemEt.pack(side=TOP, fill=X)
		self.balloon.bind(self.searchItemEt, u"Saisir les premières lettres d'un Article\npour une recherche plus précise,\nla liste est classée par désignation.")
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listItem = Listbox(s)
		self.listItem.config(yscrollcommand=scrollbar.set, width=40, selectmode=SINGLE, height=16)
		self.listItem.bind("<ButtonRelease-1>",self.selectItem)
		scrollbar.config(command=self.listItem.yview)
		self.listItem.pack()
		self.balloon.bind(self.listItem, u"Séléctionner un Article\npour le visualiser ou la modifier.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Initialisation
		self.clearFieldItem()
		self.searchItem()

	def ctrlListItemFamily(self,field):
		ItemFamilyListGUI(balloon=self.balloon, field=field, index=0, listObject=self.listObject, log=self.log, path=self.path)

	def ctrlListReference(self,field):
		ReferenceListGUI(balloon=self.balloon, field=field, index=1, listObject=self.listObject, log=self.log, path=self.path)

	def verifyItem(self):
		if self.itemValues[0].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Famille d'Articles est obligatoire !\nMerci de le compléter.")
			return False
		elif self.itemValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Réference est obligatoire !\nMerci de le compléter.")
			return False
		elif self.itemValues[2].get() == "": 
			showerror(u"Erreur de saisie", u"Le champ Désignation est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createItem(self, event=None):
		if self.verifyItem():
			if  self.deleteItemBt.config()["state"][4] == "normal":
				self.modifyItem()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme un nouvel Article ?\n" % self.itemValues[2].get()):
					Item(itemFamily=self.listObject[0],
						reference=self.listObject[1],
						designation=self.itemValues[2].get().encode("utf-8"),
						createDate=datetime.datetime.now()
					)
					self.searchItem()
				self.clearFieldItem()

	def modifyItem(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier l'Article %s ?" % self.selectedItem.designation):
			self.selectedItem.itemFamily=self.listObject[0]
			self.selectedItem.reference=self.listObject[1]
			self.selectedItem.designation=self.itemValues[2].get().encode("utf-8")   
			self.searchItem()
		self.deleteItemBt.config(state=DISABLED)
		self.clearFieldItem()

	def deleteItem(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer l'Article %s ?\nCette opération est irréversible !" % self.selectedItem.designation):
			Item.delete(self.selectedItem.id)
			self.searchItem()            
		self.deleteItemBt.config(state=DISABLED)
		self.clearFieldItem()
	# FIN de la gestion du module Item ------------------------------------------------------------------------------------------------------------------------

class ItemListGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, field=None, index=None, listObject=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Liste des Articles")
		self.balloon=balloon
		self.imgNew=PhotoImage(file="img/add_alternative_icon.gif")
		self.field=field
		self.index=index
		self.listObject=listObject
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Item-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Item-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tItemListGUI\tStart")
		self.makeListItem()

	def selectListItem(self, event):
		if self.listListItem.get(0)!="":
			result = Item.select(Item.q.id==self.idListListItem[int(self.listListItem.curselection()[0])])
			for row in result:
				self.listObject[self.index]=row
				self.field.set(row.reference)
				self.destroy()

	def searchListItem(self, event=None):
		if self.searchListItemValue.get() != "":
			self.listListItem.delete(0,END)
			self.idListListItem = []
			result = Item.select(Item.q.designation.startswith(self.searchListItemValue.get().encode("utf-8")), orderBy=Item.q.designation)
			for row in result:
				self.listListItem.insert(END, str(row.reference)+" - "+row.designation)
				self.idListListItem.append(row.id)
		else:
			self.listListItem.delete(0,END)
			self.idListListItem = []
			result = Item.select(orderBy=Item.q.designation)
			for row in result:
				self.listListItem.insert(END, str(row.reference)+" - "+row.designation)
				self.idListListItem.append(row.id)

	def makeListItem(self):
		leftFrame = Frame(self)
		Label(leftFrame, text=u"Liste des Articles").pack(side=TOP, fill=X)
		self.searchListItemValue = StringVar()
		s = Frame(leftFrame) 
		self.searchListItemEt = Entry(s,  width=32, textvariable=self.searchListItemValue, relief=GROOVE)
		self.searchListItemEt.bind("<KeyRelease>", self.searchListItem)
		self.searchListItemEt.pack(side=LEFT, fill=X)
		self.balloon.bind(self.searchListItemEt, u"Saisir les premiéres lettres d'un Articles\npour une recherche plus précise,\nla liste est classée par Désignation.")
		newItemBt=Button(s, image=self.imgNew, command=self.ctrlItem)
		newItemBt.pack(side=RIGHT)
		self.balloon.bind(newItemBt, u"Créer un nouvel Article")
		s.pack(side=TOP, fill=X)
		s = Frame(leftFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listListItem = Listbox(s)
		self.listListItem.config(yscrollcommand=scrollbar.set,width=33, selectmode=SINGLE, height=16)
		self.listListItem.bind("<ButtonRelease-1>",self.selectListItem)
		scrollbar.config(command=self.listListItem.yview)
		self.listListItem.pack()
		self.balloon.bind(self.listListItem, u"Séléctionner un Article.")
		s.pack(side=TOP, fill=X)
		leftFrame.pack()
		self.searchListItem()

	def ctrlItem(self):
		ItemGUI(balloon=self.balloon, log=self.log, path=self.path)